package com.disease.chronic.Controller;

import com.disease.chronic.Component.AiWebSocket;
import com.disease.chronic.Exception.ChronicExceptionEnum;
import com.disease.chronic.Global.Result;
import com.disease.chronic.Mappers.IndicatorsDetailMapper;
import com.disease.chronic.Service.DailySuggestService;
import com.disease.chronic.Service.DeepSeekService;
import com.disease.chronic.Service.Impl.DeepSeekServiceImpl;
import com.disease.chronic.dto.AI.MessageResponseDto;
import com.disease.chronic.pojo.DailySuggest;
import com.disease.chronic.pojo.IndicatorsDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/chat")
public class AiController {
    @Autowired
    IndicatorsDetailMapper indicatorsDetailMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    DailySuggestService dailySuggestService;

    @Autowired
    DeepSeekService deepSeekService;

    @GetMapping("/indicatorsuggest")
    public @ResponseBody Result getSuggest(@RequestParam("username") String username,@RequestParam("indicatorName") String indicatorName){
        return deepSeekService.getSuggestion(username, indicatorName);
    }
    @PostMapping("/ai")
    public @ResponseBody Result callAi(@RequestBody MessageResponseDto messageResponseDto){
        return deepSeekService.call(messageResponseDto.getMessage());
    }
    @GetMapping("/suggest")
    public @ResponseBody Result getDaySuggest(@RequestParam("username") String username){
        //查询今天的身体数据测量值
        List<IndicatorsDetail> indicatorsDetails = indicatorsDetailMapper.selectIndicatorByUsernameAndDay(username, new Date(System.currentTimeMillis()));
        if(indicatorsDetails.isEmpty()){
            return new Result(ChronicExceptionEnum.NO_DAY_MEASURE.getCode(),
                    ChronicExceptionEnum.NO_DAY_MEASURE.getMessage());
        }
        String[] strings = new String[3];

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        //判断缓存中是否存在
        if(!redisTemplate.hasKey(username+"day_suggest")) {

            //询问DeepSeek
            futures.add(deepSeekService.getDaySuggestion(username, "饮食", strings, indicatorsDetails));

            futures.add(deepSeekService.getDaySuggestion(username, "作息", strings, indicatorsDetails));

            futures.add(deepSeekService.getDaySuggestion(username, "运动", strings, indicatorsDetails));

            // 等待所有任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

//            //现在的毫秒值
//            long now = LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli();
//            //第二天凌晨的毫秒值
//            long end = LocalDate.now().plusDays(1)
//                    .atStartOfDay().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli();
//
//            long expire = end -now;
            redisTemplate.opsForHash().put(username+"day_suggest","饮食",strings[0]);
            redisTemplate.opsForHash().put(username+"day_suggest","作息",strings[1]);
            redisTemplate.opsForHash().put(username+"day_suggest","运动",strings[2]);
            //设置五分钟过期
            redisTemplate.expire(username+"day_suggest",5, TimeUnit.MINUTES);
        }else{
            strings[0] = (String) redisTemplate.opsForHash().get(username+"day_suggest","饮食");
            strings[1] = (String) redisTemplate.opsForHash().get(username+"day_suggest","作息");
            strings[2] = (String) redisTemplate.opsForHash().get(username+"day_suggest","运动");
        }
        //存入数据库持久化
        if(!dailySuggestService.hasSuggest(username,new Date(System.currentTimeMillis())))
            dailySuggestService.insertDailySuggest(username,strings[0],strings[2],strings[1]);
        return new Result<>(ChronicExceptionEnum.SUCCESS.getCode(),
                ChronicExceptionEnum.SUCCESS.getMessage(),strings);
    }

    @GetMapping("/getSuggestInWebsocket")
    public @ResponseBody Result getSuggestInWebSocket(@RequestParam("username") String username,
                                      @RequestParam("indicatorName") String indicatorName){
        if(indicatorName.equals("血压")){
            Result suggestion1 = deepSeekService.getSuggestion(username, "收缩压");
            Result suggestion2 = deepSeekService.getSuggestion(username, "舒张压");

            if(suggestion1.getCode() == 200){
                AiWebSocket.getIndicatorSuggest(username, (String) suggestion1.getData());
            }else{
                return suggestion1;
            }
            if(suggestion2.getCode() == 200){
                AiWebSocket.getIndicatorSuggest(username, (String) suggestion2.getData());

            }else {
                return suggestion2;
            }
            return new Result(ChronicExceptionEnum.SUCCESS.getCode(),
                    ChronicExceptionEnum.SUCCESS.getMessage());
        }else{
            Result suggestion = deepSeekService.getSuggestion(username, indicatorName);
            if(suggestion.getCode() == 200){
                String suggest = (String) suggestion.getData();
                AiWebSocket.getIndicatorSuggest(username, suggest);
                return new Result(ChronicExceptionEnum.SUCCESS.getCode(),
                        ChronicExceptionEnum.SUCCESS.getMessage());
            }else {
                return  suggestion;
            }
        }

    }


}

